import Mock from 'mockjs'
import express from 'express'
import path from 'path'
// import { table } from './src/mock/index.js'

// 生成 100 条模拟数据
const table = Mock.mock({
  'list|100': [
    {
      'id|+1': 1,
      name: '@cname',
      age: '@integer(20, 50)',
      'select|1-2': 2,
      'selectSearch|1-2': 2,
      'tree|1-2': 2,
      date: '@date',
      image: Mock.Random.image('200x200', '#4A7BF7', 'Avatar')
    }
  ]
}).list

// mock+express模拟服务器
// 获取当前目录的路径
const __dirname = new URL('.', import.meta.url).pathname

const app = express()

// 设置静态文件目录
app.use(express.static(path.resolve(__dirname, 'dist')))

// 所有请求都返回 Vue 的入口文件
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})

// 分页
app.get('/api/user', (req, res) => {
  const {
    current = 1,
    size = 10,
    name,
    age,
    select,
    selectSearch,
    tree,
    date
  } = req.query
  let data = [...table]

  // 1. 过滤逻辑
  if (name) data = data.filter((item) => item.name.includes(name))
  if (age) data = data.filter((item) => item.age === age)
  if (select) data = data.filter((item) => item.select === select)
  if (selectSearch)
    data = data.filter((item) => item.selectSearch === selectSearch)
  if (tree) data = data.filter((item) => item.tree === tree)
  if (date) data = data.filter((item) => item.date === date)

  // 2. 分页逻辑
  const start = (current - 1) * size
  const end = start + parseInt(size)
  const result = data.slice(start, end)

  // 3. 返回结果
  res.json({
    code: 200,
    total: data.length,
    current: parseInt(current),
    size: parseInt(size),
    data: result
  })
})

const port = 3000
// 启动服务器
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`)
})
